// 导航区域
free_Web.Function.ReadArea = {
    Config: {
        DefineArea: [
            {
                Name: "导航区",
                TagName: ".mainNav",
                img: "Br_ReadArea_menu.png",
            },
            {
                Name: "交互区",
                TagName: ".s-form",
                img: "Br_ReadArea_interaction.png",
            },
            {
                Name: "正文区",
                TagName: ".mainContent",
                img: "Br_ReadArea_interaction.png",
            },
            {
                Name: "视窗区",
                TagName: ".freewebinfolistarea",
                img: "Br_ReadArea_interaction.png",
            },
            {
                Name: "正文区",
                TagName: ".articleCon",
                img: "Br_ReadArea_interaction.png"
            }
            //{
            //    Name: "测试区",
            //    TagName: "#indXwdt",
            //    img: "Br_ReadArea_interaction.png",
            //}
        ],
        tools: [
            {
                id: "Br_Area",
                fun: "javascript:free_Web.Function.ReadArea.Start();",
                title: "开启读屏",
                minTitle: "读屏",
                entitle: "关闭读屏",
                img: "Br_ReadArea.png",
                key: "Shift+P",
                dir: "",
                keycode: 80,
            },
        ],
        InsterClassName: "read-area",
        TagIdPrefix: "area-",
        FocusClassName: "read-area-border",
        TabAreaSelectedName: "read-area-selected-tab",
        TabAreaSelectItemName: "read-rea-selected-tab-item"
    },
    SelectItems: [],
    areaList: [],
    currentArea: null,
    status: false,
    enableTab: false,
    initTab: false,
    load: function () {
        var array = this.Config.DefineArea;
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            var area = {
                Name: element.Name,
                Id: this.Config.TagIdPrefix + element.TagName,
                Tag: element.TagName,
                img: element.img,
                TagElements: [],
                Index: -1,
            };

            var tagNameSplits = element.TagName.split("|");
            var areaTags = [];
            for (var i = 0; i < tagNameSplits.length; i++) {
                var tags = $(tagNameSplits[i]);
                for (var j = 0; j < tags.length; j++) {
                    if ($(tags[j]).children().length == 0) {
                        if (!element.Single) {
                            continue;
                        }
                    }

                    areaTags.push(tags[j]);
                }
            }

            if (areaTags.length > 0) {
                for (let j = 0; j < areaTags.length; j++) {
                    const areaElement = areaTags[j];
                    if (!$(areaElement).is(":hidden")) {
                        area.TagElements.push(areaElement);
                    }
                    $(areaElement).attr("data-pos-top", Math.round($(areaElement).offset().top / 20))
                    $(areaElement).attr("data-pos-left", Math.round($(areaElement).offset().left / 20))
                }

                var resArray = [];
                for (var i = 0; i < area.TagElements.length; i++) {
                    var rele = area.TagElements[i];
                    var exist = false;
                    for (var ral in resArray) {
                        if ($(rele).attr("data-pos-top") == $(resArray[ral]).attr("data-pos-top") && $(rele).attr("data-pos-left") == $(resArray[ral]).attr("data-pos-left")) {
                            exist = true;
                        }
                    }
                    if (exist) continue;
                    resArray.push(rele);
                }
                area.TagElements = resArray;
                this.areaList.push(area);
            }
        }

        array = this.areaList;
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            var ulTag = $("." + this.Config.InsterClassName);
            var showIcon =
                "<li>" +
                "<a id='" +
                element.Id +
                "'" +
                "href=\"javascript:free_Web.Function.ReadArea.FindArea('" +
                element.Id +
                "')\"><img src='/free_Web/images/" +
                element.img +
                "'></a><p>" +
                element.Name +
                "</p><lable>Alt + " + (index + 1) + "</lable>" +
                "</li> ";

            ulTag.append(showIcon);
        }
    },
    KeyboardEventRegister: false,
    KeyboardEvent: function () {
        if (!this.KeyboardEventRegister) {
            document.addEventListener('keydown',
                function keyListener(e) {
                    if (this.enableTab) {
                        var currkey = 0,
                            e = e || event;
                        currkey = e.key;
                        if (e.altKey) {
                            if (!isNaN(currkey)) {
                                var k = parseInt(currkey);
                                var li = $("#free_Web_box .free_Web_tool .read-area").find("li")[k - 1];
                                if (li) {
                                    $(li).find("a")[0].click();
                                }
                            }
                        }
                    }
                });
            this.KeyboardEventRegister = true;
        }
    },
    toolhtml: function () {
        s = "<ul class='Br_Area_ul'>";
        for (var i = 0; i < this.Config.tools.length; i++) {
            s +=
                "<li class='Br_Area_li'><a id='" +
                this.Config.tools[i].id +
                "' href='" +
                this.Config.tools[i].fun +
                "' title='" +
                this.Config.tools[i].title +
                "（" +
                this.Config.tools[i].key +
                "）'><img src='/free_Web/images/" +
                this.Config.tools[i].img +
                "' dir='" +
                this.Config.tools[i].dir +
                "'></a><p>读屏</p></li>";
        }
        s += "</ul>";
        return $(s);
    },
    show: function () {
        var But = $("#Br_Area");
        var Fpbar_En = $("#Fpbar_En");
        if (this.status) {
            But.attr("title", "关闭读屏(" + this.Config.tools[0].key + ")");
            But.addClass("active");
        } else {
            But.attr("title", "开启读屏(" + this.Config.tools[0].key + ")");
            But.removeClass("active");
        }

        if (!this.IStransEn) {
            Fpbar_En.addClass("en");
        } else {
            Fpbar_En.removeClass("en");
        }

        $("#" + this.Config.menuBoxid)
            .find("li")
            .removeClass("active");
        $("#" + this.Config.menuBoxid)
            .find("li")
            .eq(this.ItemNum)
            .addClass("active");
    },
    down: function () {
        $("#free_Web_box_sub").height("96px");
        free_Web.Function.audioplay.audio("您已关闭读屏设置开关");
        this.areaList = [];
        $("." + this.Config.InsterClassName).remove();
        $(".free_Web_tool").children().remove();
        var array = $(".free_Web_tool_hide").children();
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            $(".free_Web_tool").append($(element));
        }
        $(".free_Web_tool_hide").remove();
        this.show();
    },
    clear: function () {
        $(".Br_Area_ul").remove();
    },
    Start: function () {
        // 子站定义此方法，实现自己的选择区域。
        if (free_Web.Function.ReadArea.Config.CustomDefineArea) {
            free_Web.Function.ReadArea.Config.SourceDefineArea = free_Web.Function.ReadArea.Config.DefineArea;
            free_Web.Function.ReadArea.Config.DefineArea = free_Web.Function.ReadArea.Config.CustomDefineArea;
        }
        $("#free_Web_box_sub").height("120px");
        if (free_Web.Function.show.status) {
            if (!this.status) {
                $(".Br_Area_ul").prepend(
                    "<li><ul class='" +
                    this.Config.InsterClassName +
                    "' hidden></ul></li>"
                );

                $("body").append("<ul class='free_Web_tool_hide' hidden></ul>");

                var array = $(".free_Web_tool").children();
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];

                    $(".free_Web_tool_hide").append($(element).clone(true));
                    // element.remove();
                }

                function exclude(param, element) {
                    var arraryExclude = param.split(",");
                    for (let index = 0; index < arraryExclude.length; index++) {
                        param = arraryExclude[index];

                        if (
                            $(element).find(param).length > 0 ||
                            $(element).find(param).length > 0 ||
                            $(element).hasClass(param)
                        )
                            return true;
                    }
                }

                var array = $(".free_Web_tool").children();
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    if (
                        exclude(
                            "#Br_BarTitle,#Br_Area,.read-area,read-area,#Br_close,#Br_help",
                            element
                        )
                    ) {
                        continue;
                    }

                    $(element).remove();
                }

                this.load();
                this.status = true;

                $("." + this.Config.InsterClassName).show();
                free_Web.Function.audioplay.audio("您已开启读屏功能");
                this.show();
                free_Web.tool_Box_sub.slideDown(500);
                free_Web.tool_Box.slideDown(500);
            } else {
                this.clear();
                free_Web.Function.audioplay.audio("您已关闭读屏功能");
            }
        }
    },
    DefaultStart: function () {
        this.enableTab = true;
        if (!this.initTab) {
            this.KeyboardEvent();
            if (free_Web.Function.show.status) {
                this.AddOnceEvent("mousedown,keydown");
                free_Web.Function.InsideLabel.init();
            }

            this.initTab = true;
        }
    },
    clear: function () {
        this.status = false;
        this.ISItemsShow = false;
        this.down();
        this.show();
    },
    AddOnceEvent: function (ent) {
        var array = ent.split(",");
        for (let index = 0; index < array.length; index++) {
            var array = ent.split(",");
            const element = array[index];
            window.addEventListener(element, function (e) {
                if (e.code == 'Enter' || e.code == 'NumpadEnter') {
                    free_Web.Function.ReadArea.EnterKeyDown();
                    return;
                }

                if (e.code == 'Tab') {
                    free_Web.Function.ReadArea.TabKeyFunction(e);
                    this.event.preventDefault();
                }
                else {
                    free_Web.Function.ReadArea.TabKeyClear();
                }
                if (free_Web.Function.ReadArea.currentArea) {
                    $(free_Web.Function.ReadArea.currentArea).removeClass(
                        free_Web.Function.ReadArea.Config.FocusClassName
                    );
                }
            });
        }
    },
    TabKeyFunction: function (e) {
        if (!this.enableTab) {
            return;
        }
        var focusElements = $("." + free_Web.Function.ReadArea.Config.FocusClassName);
        if (focusElements.length != 0) {
            focusElements.removeClass(free_Web.Function.ReadArea.Config.FocusClassName);
            focusElements.addClass(free_Web.Function.ReadArea.Config.TabAreaSelectedName);
        } else {
            // 确定没有任何元素。
            $("body").addClass(free_Web.Function.ReadArea.Config.TabAreaSelectedName);
        }

        var tabAreaSelecteds = $("." + free_Web.Function.ReadArea.Config.TabAreaSelectedName);

        if (this.SelectItems.length == 0) {
            var items = tabAreaSelecteds.find(".Shimen-Pointer-Label");
            var inputItems = tabAreaSelecteds.find(".INPUT-Shimen-Pointer-Label");
            for (var i = 0; i < inputItems.length; i++) {
                var element = inputItems[i];
                if (!$(element).is(":hidden")) {
                    this.SelectItems.push(element);
                }
            }

            for (var i = 0; i < items.length; i++) {
                var element = items[i];
                if (!$(element).is(":hidden")) {
                    this.SelectItems.push(element);
                }
            }
            this.SelectItemIndex = 0;
            for (var i = 0; i < this.SelectItems.length; i++) {
                var element = this.SelectItems[i];
                $(element).attr("data-pos-top", Math.round($(element).offset().top / 20))
                $(element).attr("data-pos-left", Math.round($(element).offset().left / 20))
            }

            this.SelectItems.sort(function (a, b) {
                var top1 = parseInt(a.getAttribute('data-pos-top'));
                var top2 = parseInt(b.getAttribute('data-pos-top'));
                var left1 = parseInt(a.getAttribute('data-pos-left'));
                var left2 = parseInt(b.getAttribute('data-pos-left'));
                if (top1 < top2) {
                    return -1;
                }
                else if (top1 == top2 && left1 < left2) {
                    return -1;
                }
                else {
                    return 1;
                }

                return 0;
            });
        }

        $(this.currentSelectItem).removeClass(free_Web.Function.ReadArea.Config.TabAreaSelectItemName);
        if (!this.SelectItemIndex) {
            this.SelectItemIndex = 0;
        } else if (this.SelectItemIndex >= this.SelectItems.length) {
            this.SelectItemIndex = 0;
        }

        if (this.SelectItems.length != 0) {
            $(this.currentSelectItem).blur();
            var ele = this.SelectItems[this.SelectItemIndex];
            $(ele).addClass(free_Web.Function.ReadArea.Config.TabAreaSelectItemName)
            $(ele).focus();
            //$(ele).mouseover();
            e.stopPropagation();
            this.currentSelectItem = ele;
            this.SelectItemIndex++;
            this.TabSelectMsg(ele)
        }
    },
    TabKeyClear: function () {
        this.SelectItems = [];
        this.SelectItemIndex = 0;
        $("." + free_Web.Function.ReadArea.Config.TabAreaSelectItemName).removeClass(free_Web.Function.ReadArea.Config.TabAreaSelectItemName);
        $("." + free_Web.Function.ReadArea.Config.TabAreaSelectedName).removeClass(free_Web.Function.ReadArea.Config.TabAreaSelectedName);
        $(".voice-active").removeClass("voice-active");
    },
    TabSelectMsg: function (ele) {
        var str = free_Web.Function.Read.getReadContent(ele);
        //ele = $(ele).find(".Shimen-Pointer-Label");
        $("voice").removeClass("voice-active");
        $(ele).addClass("voice-active");
        this.EnterAreaShow(str);
    },
    EnterKeyDown: function () {
        $(this.currentSelectItem).parent()[0].click();
    },
    EnterAreaShow: function (msg) {
        free_Web.Function.audioplay.audio(msg);
        $("#tooltips_show").html(msg);
    },
    FindArea: function (id) {
        var array = this.areaList;

        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            if (element.Id == id) {
                var idx = element.Index;
                idx++;
                if (idx < element.TagElements.length) {
                    element.Index++;
                } else {
                    element.Index = 0;
                    idx = 0;
                }

                var ele = element.TagElements[idx];
                $(ele).addClass(this.Config.FocusClassName);
                var top = $(ele).offset().top;

                //// 计算居中位置。
                //var el = $(ele).offset().top + $(ele).height() / 2;
                //var windowScrollTop = document.body.scrollTop;
                //var wHeight = window.innerHeight / 2;
                //var vtop = windowScrollTop - (wHeight - el);
                //var scol = $(document).scrollTop();
                var vtop = top - 130;
                if (!$("#JS_hideBox2").hasClass("topNav-fixed")) {
                    vtop = vtop - 54;
                }
                $("html,body").stop(true, false).animate({ scrollTop: vtop }, 220, "swing");
                $(ele).focus();
                this.currentArea = ele;
                var likeCount = $(ele).find("a").length;
                this.EnterAreaShow(
                    "您已进入" +
                    element.Name +
                    ",本区域包含" +
                    likeCount +
                    "链接。"
                );
                return;
            }
        }
    },
};